#include <iostream>
#include <cstring>
#include <algorithm>
#include <cstdio>
#include <cmath>
#include <vector>
#include <list>
#include <queue>
#include <stack>
#include <map>
#include <unordered_map>
#include <unordered_set>
#include <set>
#include <bitset>
#include <utility>
using namespace std;

#define mm(a, n) memset(a, n, sizeof a)
#define mk(a, b) make_pair(a, b)

const double eps = 1e-6;
const int INF = 0x3f3f3f3f;

typedef long long LL;
typedef unsigned long long ULL;
typedef pair<int, int> PII;
typedef pair<LL, LL> PLL;
typedef pair<int, LL> PIL;

inline void quickread() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
}

const int N = 1e5 + 10;

struct Node {
    char data;
    int next;
} node[N];

bool st[N];
int n, h1, h2;

inline void solution() {
    mm(st, false);
    cin >> h1 >> h2 >> n;

    for (int i = 0; i < n; i ++ ) {
        int idx;
        cin >> idx;
        cin >> node[idx].data >> node[idx].next;
    }

    int p = h1;
    while (p != -1) {
        st[p] = true;
        p = node[p].next;
    } 
    p = h2;
    while (p != -1) {
        if (st[p]) {
            printf("%05d", p);
            return ;
        }
        p = node[p].next;
    }
    puts("-1");
    return ;
}

int main() {
    freopen("input.txt", "r", stdin);
    quickread();
    solution();
    return 0;
}